package com.atguigu.guli.service.statistics.service.impl;

import com.atguigu.guli.service.base.exception.GuliException;
import com.atguigu.guli.service.base.result.R;
import com.atguigu.guli.service.base.result.ResultCodeEnum;
import com.atguigu.guli.service.statistics.entity.Daily;
import com.atguigu.guli.service.statistics.mapper.DailyMapper;
import com.atguigu.guli.service.statistics.service.DailyService;
import com.atguigu.guli.service.statistics.service.UcenterFeignClient;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 网站统计日数据 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2021-08-16
 */
@Service
public class DailyServiceImpl extends ServiceImpl<DailyMapper, Daily> implements DailyService {

    @Autowired
    UcenterFeignClient ucenterFeignClient;
    @Override
    public void genDaily(String day) {
        R r = ucenterFeignClient.countRegisterMember(day);
        Daily daily = new Daily();
        daily.setDateCalculated(day);//统计日期
        daily.setVideoViewNum(RandomUtils.nextInt(3000,10000));//视频点播次数
        daily.setCourseNum(RandomUtils.nextInt(5,100));//新增课程的数量
        daily.setLoginNum(RandomUtils.nextInt(1000 , 5000));// 每日登陆用户数量
        if(!r.getSuccess()){
            throw new GuliException(ResultCodeEnum.COUNT_REGISTER_ERROR);
        }
        daily.setRegisterNum(Integer.parseInt(r.getData().get("count").toString()));
        baseMapper.insert(daily);
    }

    @Override
    public Map<String, Object> getStatistics(String begin, String end) {
        LambdaQueryWrapper<Daily> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.gt(Daily::getDateCalculated,begin);
        queryWrapper.lt(Daily::getDateCalculated,end);

        List<Daily> dailies = baseMapper.selectList(queryWrapper);
        List<String> dates = new ArrayList();
        List<Integer> registerNums = new ArrayList();
        List<Integer> loginNums = new ArrayList();
        List<Integer> videoViewNums = new ArrayList();
        List<Integer> courseNums = new ArrayList();
        dailies.forEach(daily -> {
            dates.add(daily.getDateCalculated());
            registerNums.add(daily.getRegisterNum());
            loginNums.add(daily.getLoginNum());
            videoViewNums.add(daily.getVideoViewNum());
            courseNums.add(daily.getCourseNum());
        });
        Map<String,Object> map = new HashMap<>();
        map.put("dates",dates);
        map.put("registerNums",registerNums);
        map.put("loginNums",loginNums);
        map.put("videoViewNums",videoViewNums);
        map.put("courseNums",courseNums);
        return map;
    }
}
